package com.example.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/test")
@Tag(name = "接口测试", description = "用于测试各种API接口的功能")
public class TestController {

    @GetMapping("/health")
    @Operation(summary = "健康检查")
    public ResponseEntity<Map<String, Object>> healthCheck() {
        Map<String, Object> health = new HashMap<>();
        health.put("status", "UP");
        health.put("timestamp", LocalDateTime.now());
        health.put("version", "1.0.0");
        health.put("environment", "development");
        
        // 检查各个组件状态
        health.put("components", Map.of(
            "database", "UP",
            "redis", "UP",
            "fileSystem", "UP",
            "externalAPI", "UP"
        ));
        
        return ResponseEntity.ok(health);
    }

    @GetMapping("/info")
    @Operation(summary = "系统信息")
    public ResponseEntity<Map<String, Object>> systemInfo() {
        Map<String, Object> info = new HashMap<>();
        info.put("applicationName", "洗护管理系统");
        info.put("version", "1.0.0");
        info.put("buildTime", "2024-12-01 10:00:00");
        info.put("javaVersion", System.getProperty("java.version"));
        info.put("springBootVersion", "3.2.0");
        
        // 运行时信息
        Runtime runtime = Runtime.getRuntime();
        info.put("runtime", Map.of(
            "totalMemory", runtime.totalMemory() / 1024 / 1024 + "MB",
            "freeMemory", runtime.freeMemory() / 1024 / 1024 + "MB",
            "maxMemory", runtime.maxMemory() / 1024 / 1024 + "MB",
            "processors", runtime.availableProcessors()
        ));
        
        return ResponseEntity.ok(info);
    }

    @GetMapping("/endpoints")
    @Operation(summary = "获取所有API端点")
    public ResponseEntity<Map<String, Object>> getAllEndpoints() {
        Map<String, Object> endpoints = new HashMap<>();
        
        // 认证相关
        endpoints.put("auth", List.of(
            "POST /api/auth/login - 用户登录",
            "POST /api/auth/register - 用户注册",
            "POST /api/auth/logout - 用户登出",
            "GET /api/auth/me - 获取当前用户信息"
        ));
        
        // 洗护订单
        endpoints.put("laundry", List.of(
            "GET /api/laundry/orders - 获取订单列表",
            "POST /api/laundry/orders - 创建订单",
            "GET /api/laundry/orders/{id} - 获取订单详情",
            "PUT /api/laundry/orders/{id} - 更新订单",
            "DELETE /api/laundry/orders/{id} - 删除订单"
        ));
        
        // 服务管理
        endpoints.put("services", List.of(
            "GET /api/wash/services - 获取服务列表",
            "POST /api/wash/services - 创建服务",
            "GET /api/wash/services/{id} - 获取服务详情",
            "PUT /api/wash/services/{id} - 更新服务"
        ));
        
        // 设备管理
        endpoints.put("equipment", List.of(
            "GET /api/wash/equipment - 获取设备列表",
            "POST /api/wash/equipment - 创建设备",
            "GET /api/wash/equipment/{id} - 获取设备详情",
            "PUT /api/wash/equipment/{id} - 更新设备"
        ));
        
        // 库存管理
        endpoints.put("inventory", List.of(
            "GET /api/wash/inventory - 获取库存列表",
            "POST /api/wash/inventory - 创建库存物品",
            "GET /api/wash/inventory/{id} - 获取库存详情",
            "PUT /api/wash/inventory/{id} - 更新库存"
        ));
        
        // 财务管理
        endpoints.put("finance", List.of(
            "GET /api/finance/overview - 财务总览",
            "GET /api/finance/income - 收入列表",
            "POST /api/finance/income - 创建收入记录",
            "GET /api/finance/expense - 支出列表",
            "POST /api/finance/expense - 创建支出记录"
        ));
        
        // 营销管理
        endpoints.put("marketing", List.of(
            "GET /api/marketing/coupons - 优惠券列表",
            "POST /api/marketing/coupons - 创建优惠券",
            "GET /api/marketing/statistics - 营销统计"
        ));
        
        return ResponseEntity.ok(endpoints);
    }

    @PostMapping("/mock-data")
    @Operation(summary = "生成模拟数据")
    public ResponseEntity<Map<String, Object>> generateMockData(
            @RequestBody Map<String, Object> options) {
        
        String dataType = (String) options.getOrDefault("type", "all");
        Integer count = (Integer) options.getOrDefault("count", 10);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "模拟数据生成成功");
        result.put("dataType", dataType);
        result.put("generatedCount", count);
        result.put("generatedAt", LocalDateTime.now());
        
        return ResponseEntity.ok(result);
    }

    @PostMapping("/reset-data")
    @Operation(summary = "重置测试数据")
    public ResponseEntity<Map<String, Object>> resetTestData() {
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "测试数据重置成功");
        result.put("resetAt", LocalDateTime.now());
        
        return ResponseEntity.ok(result);
    }

    @GetMapping("/performance")
    @Operation(summary = "性能测试")
    public ResponseEntity<Map<String, Object>> performanceTest(
            @RequestParam(defaultValue = "1000") int iterations) {
        
        long startTime = System.currentTimeMillis();
        
        // 模拟一些计算
        for (int i = 0; i < iterations; i++) {
            Math.sqrt(i);
        }
        
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;
        
        Map<String, Object> result = new HashMap<>();
        result.put("iterations", iterations);
        result.put("duration", duration + "ms");
        result.put("averageTime", (double) duration / iterations + "ms");
        result.put("timestamp", LocalDateTime.now());
        
        return ResponseEntity.ok(result);
    }

    @GetMapping("/database-test")
    @Operation(summary = "数据库连接测试")
    public ResponseEntity<Map<String, Object>> databaseTest() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 这里应该实际测试数据库连接
            result.put("status", "SUCCESS");
            result.put("message", "数据库连接正常");
            result.put("connectionTime", "15ms");
            result.put("databaseType", "H2");
            result.put("timestamp", LocalDateTime.now());
        } catch (Exception e) {
            result.put("status", "ERROR");
            result.put("message", "数据库连接失败: " + e.getMessage());
            result.put("timestamp", LocalDateTime.now());
        }
        
        return ResponseEntity.ok(result);
    }

    @PostMapping("/send-notification")
    @Operation(summary = "测试通知发送")
    public ResponseEntity<Map<String, Object>> testNotification(
            @RequestBody Map<String, Object> notificationData) {
        
        String type = (String) notificationData.get("type");
        String recipient = (String) notificationData.get("recipient");
        String message = (String) notificationData.get("message");
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "通知发送成功");
        result.put("type", type);
        result.put("recipient", recipient);
        result.put("sentAt", LocalDateTime.now());
        
        return ResponseEntity.ok(result);
    }

    @GetMapping("/error-test")
    @Operation(summary = "错误处理测试")
    public ResponseEntity<Map<String, Object>> errorTest(
            @RequestParam(defaultValue = "none") String errorType) {
        
        switch (errorType) {
            case "runtime":
                throw new RuntimeException("这是一个运行时异常测试");
            case "null":
                throw new NullPointerException("这是一个空指针异常测试");
            case "illegal":
                throw new IllegalArgumentException("这是一个非法参数异常测试");
            default:
                Map<String, Object> result = new HashMap<>();
                result.put("message", "错误处理测试正常");
                result.put("errorType", errorType);
                result.put("timestamp", LocalDateTime.now());
                return ResponseEntity.ok(result);
        }
    }

    @GetMapping("/cache-test")
    @Operation(summary = "缓存测试")
    public ResponseEntity<Map<String, Object>> cacheTest() {
        Map<String, Object> result = new HashMap<>();
        result.put("cacheStatus", "ENABLED");
        result.put("cacheType", "In-Memory");
        result.put("cacheSize", "1024KB");
        result.put("hitRate", "85.5%");
        result.put("timestamp", LocalDateTime.now());
        
        return ResponseEntity.ok(result);
    }

    @PostMapping("/file-upload-test")
    @Operation(summary = "文件上传测试")
    public ResponseEntity<Map<String, Object>> fileUploadTest() {
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "文件上传功能正常");
        result.put("maxFileSize", "10MB");
        result.put("supportedTypes", List.of("jpg", "png", "pdf", "doc", "xls"));
        result.put("timestamp", LocalDateTime.now());
        
        return ResponseEntity.ok(result);
    }
}
